const db = uniCloud.database()
module.exports = {
	getById: async (collection, id, transaction) => {
		let db2 = transaction || db;
		try{
			let res = await db2.collection(collection).doc(id).get();
			if (Array.isArray(res.data)) {
				return res.data[0];
			} else {
				return res.data
			}
		}catch(e){
			throw e;
		}
	},
	getOne: async (collection, query) => {
		try{
			let res = await db.collection(collection).where(query).get();
			if (res.data.length) {
				return res.data[0];
			}
		} catch(e){
			throw e;
		}
	},
	getList: async (collection, query) => {
		try{
			let res = await db.collection(collection).where(query).get();
			return res.data;
		} catch(e){
			throw e;
		}
	},
	getPage: async (collectionName, pageNum, pageSize, query, sorts) => {
		try{
			let countRes = await db.collection(collectionName).where(query).count();
			let page = {
				total: countRes.total,
				list: []
			}
			if (countRes.total) {
				var collection = db.collection(collectionName);
				collection = collection.where(query).skip((pageNum - 1) * pageSize).limit(pageSize);
				if (sorts) {
					sorts.forEach(item => {
						collection = collection.orderBy(item.field, item.order);
					})
				}
				let listRes = await collection.get();
				page.list = listRes.data
			}
			return page;
		}catch(e){
			throw e;
		}
	},
	getCount: async (collection, query) => {
		try{
			let res = await db.collection(collection).where(query).count();
			return res.total;
		}catch(e){
			throw e;
		}
	},
	insert: async (collection, data, transaction) => {
		let db2 = transaction || db;
		try{
			let res = await db2.collection(collection).add(data);
			data._id = res.id;
		}catch(e){
			throw e;
		}
	},
	update: async (collection, data, transaction) => {
		let db2 = transaction || db;
		try{
			let t = Object.assign({}, data);
			delete t._id;
			await db2.collection(collection).doc(data._id).update(t);
		}catch(e){
			throw e;
		}
	},
	runTransaction: async (callback) => {
		console.log("开始事务");
		const transaction = await db.startTransaction();
		try{
			await callback(transaction);
			transaction.commit();
			console.log("提交事务");
		}catch(e){
			transaction.rollback();
			console.log("回滚事务");
			throw e;
		}
	}
}
